package com.websocet.controller;

import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: 陈玉鹏
 * @Description: TODO
 * @DateTime: 2023/1/31 22:43
 */
@Slf4j
@Component
@ServerEndpoint("/info2/{userName}")    // 指定websocket 连接的url
public class WebSocketServer2 {

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    @JsonBackReference
    private static Map<String, WebSocketServer2> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userName
     */
    private String userName = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {
        log.info("客户端：{}{}连接成功", session.getId(), userName);
    }

    @OnClose
    public void onClose(Session session, @PathParam("userName") String userName) {
        log.info("客户端：{}{}连接成功", session.getId(), userName);
    }

    @OnMessage
    public void onMsg(String message, Session session,@PathParam("userName") String userName) {
        log.info("从客户端：{} 收到<--:{}", session.getId(), message);

        String send = message.toUpperCase();
        String result = "客户：%s您好，来自server 的消息:%s";
        result = String.format(result, session.getId(), send);
        sendMessage(session,userName,result);

        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

            }
        };
        timer.schedule(timerTask,2);

        result = "return 来自server 的消息： + result;";
        sendMessage(session,userName,result);
    }

    /**
     * 向指定客户端发送消息
     * <p>
     * // * @param userName
     * //* @param message
     */
    public static void sendMessage(Session session,String userName, String message) {
        try {
            WebSocketServer2 webSocketService = webSocketMap.get(userName);
            if (webSocketService != null) {
                webSocketService.getSession().getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public Session getSession() {
        return session;
    }
}

